function [equity, debt, firm, lambda, vf_error] = equity_value(bParams,oParams,setts,upMat,f,c,equity_in,debt_in,recovery_value)
% Calculates the equity value function using value function iteration

% Variables:
% bParams,oParams,setts		see readme
% upMat		updating matrix equity value
% f			rate of creative destruction
% c			coupon
% equity_in	initial guess equity value
% debt_in	initial guess debt value
% recovery_value recovery value

% Set parameters
	pbar = oParams.pbar;

	gamma = bParams.gamma;
	beta = bParams.beta;
	xi = bParams.xi;

	e_prec = setts.e_prec;
	n_lambda = setts.n_lambda;

	L = upMat.L;
    bin_prob = upMat.bin_prob;

% Starting values
	equity = equity_in;
	vf_error = e_prec + 1;


% Value function iteration
	while vf_error > e_prec

% Save old equity value
		equity0 = equity;

% Optimal R&D intensity and quality
		VAL = OPT(oParams,upMat,equity);
        lambda = zeros(1,pbar+1);
		for i = 0:pbar
			[~,index] = max(VAL(n_lambda*i+1:n_lambda*(i+1)));
			lambda(i+1) = L(n_lambda*i+index);
        end

% Policy function iteration
		q_mat = q((0:pbar),lambda,gamma,beta);
		for j = 1:80
			[equity_new] = equity_update(bParams,oParams,f,c,lambda,equity,bin_prob,q_mat);
			equity = equity_new;
		end

% Calculate error
		vf_error = sum(abs((equity0 - equity)/sum(equity0)));
	end

% Calculate debt and firm value
	if setts.nodebt==1
		debt = zeros(1,pbar+1);
	else
		debt = debt_value(oParams,setts,f,c,lambda,equity,debt_in,bin_prob,recovery_value);
	end
	firm = equity + (1-xi) * debt;

end

